package com.ljw.vendingmachine.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.ljw.vendingmachine.MainActivity;
import com.ljw.vendingmachine.R;
import com.ljw.vendingmachine.bean.MessageEvent;
import com.ljw.vendingmachine.utils.Constant;
import com.ljw.vendingmachine.utils.LogUtil;
import com.ljw.vendingmachine.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.security.PublicKey;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;

public class WebSocketService extends Service {


    private EchoWebSocketListener socketListener;
    private Timer timer;
    private WebSocket mSocket;

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        LogUtil.e("App","webSocket服务开启");

    }

    public void initialClient() {

        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(3, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(3, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(3, TimeUnit.SECONDS)//设置连接超时时间
                .build();

        Request request = new Request.Builder().url("ws://"+SPUtils.get(getApplicationContext(), Constant.IP, "").toString() +":"+SPUtils.get(getApplicationContext(), Constant.PORT, "").toString()+ "?name="+SPUtils.get(getApplicationContext(), Constant.DEVICEID, "").toString()).build();

        try {
            if (socketListener!=null)
            socketListener = null;
            if (mSocket!=null){
                LogUtil.e("App","已有连接即将断开");
                mSocket.close(1000,"主动关闭");
            }
        }catch (Exception s){
            LogUtil.e("webSocket：","webSocket关闭失败");
        }
        socketListener = new EchoWebSocketListener();
        mSocket = mOkHttpClient.newWebSocket(request, socketListener);
        if (mSocket!=null)  LogUtil.e("App","websocket连接成功！");
        mOkHttpClient.dispatcher().executorService().shutdown();
        String format = String.format(Constant.COMD_LOGIN, SPUtils.get(getApplicationContext(), Constant.DEVICEID, "").toString());
        LogUtil.e("发送登陆命令",format);
        mSocket.send(format);

          mSocket.send(Constant.COMD_GET_MAIN_GOODS);
        //创建心跳发送

        if (timer==null){
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {

                                MessageEvent mes = new MessageEvent();
                                mes.setCode(Constant.SEND_CMD);
                                mes.setData(Constant.COMD_HEART);
                                EventBus.getDefault().post(mes);



                }
            },0,25000);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.e("App","服务onStartCommand");
        initialClient();
        Notification.Builder builder = new Notification.Builder
                (this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, MainActivity.class);

        builder.setContentIntent(PendingIntent.
                getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
                        R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
                .setContentTitle("售货机通讯进程") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText("售货机通讯进程") // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        startForeground(110, notification);
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        LogUtil.e("serviceonDestroy", "serviceonDestroy");
        super.onDestroy();
        stopForeground(true);
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onReceiveComd(MessageEvent event) {
        //判断是否是发送命令的编码
        if (Constant.SEND_CMD == event.getCode()) {
            send(event.getData().toString());
        }

        if (Constant.CONNECT==event.getCode()){
            initialClient();
        }


    }



    public void send(String str){
        try{

//                boolean send = mSocket.send(str);
//                LogUtil.e("sendResult:",send+"");
            if (mSocket==null||!mSocket.send(str)){
             initialClient();

            } else
                LogUtil.e("mSocketSend:",str);
        }catch (Exception e){
            LogUtil.e("mSocketException","mSocket  Exception");
        }


    }
}
